package cn.edu.nju.software.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;
import javax.sql.DataSource;

import cn.edu.nju.software.bean.show.BookItemInOrder;
import cn.edu.nju.software.bean.storage.Book;
import cn.edu.nju.software.dao.intf.OrderBookDao;

public class OrderBookDaoImpl implements OrderBookDao {

	private DataSource ds;

	public OrderBookDaoImpl() {
		try {
			ds = JDBCUtil.getDataSource();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public List<BookItemInOrder> getOrderBooks(int id) throws SQLException {
		List<BookItemInOrder> list = new ArrayList<BookItemInOrder>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = ds.getConnection();
			con.setAutoCommit(false);
			pstmt = con
					.prepareStatement("SELECT b.id, b.isbn, b.title, b.author, "
							+ "b.publisher, b.catg_id, b.abstract, b.price, b.sales, b.aval_date, "
							+ "b.in_stock, b.pic_path, b.attach, ob.quantity, ob.price FROM book b, "
							+ "order_book ob WHERE b.id = ob.book_id AND ob.order_id = ?");
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				list.add(new BookItemInOrder(new Book(rs.getInt(1), rs
						.getString(2), rs.getString(3), rs.getString(4), rs
						.getString(5), rs.getInt(6), rs.getString(7), rs
						.getBigDecimal(8), rs.getInt(9), rs.getTimestamp(10),
						rs.getInt(11), rs.getString(12), rs.getString(13)), rs
						.getInt(14), rs.getBigDecimal(15)));
			}
			con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			con.rollback();
			throw e;
		} finally {
			JDBCUtil.closeResultSet(rs);
			JDBCUtil.closeStatement(pstmt);
			JDBCUtil.closeConnection(con);
		}
		return list;
	}

}
